package com.cgnpc.scp.hse.controller;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.utils.FileUtils;
import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.utils.UrlUtil;
import com.cgnpc.cud.annotation.OperatorType;
import com.cgnpc.cud.annotation.UBA;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.common.bean.ScpApiResult;
import com.cgnpc.scp.common.bean.ScpFileInfoVO;
import com.cgnpc.scp.common.mybatis.entity.ScpCommonFileUpload;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.service.AppConstantService;
import com.cgnpc.scp.common.service.DownloadFileService;
import com.cgnpc.scp.common.service.FileCenterService;
import com.cgnpc.scp.common.service.IScpCommonFileUploadService;
import com.cgnpc.scp.common.utils.AjaxResultUtil;
import com.cgnpc.scp.common.utils.DateUtil;
import com.cgnpc.scp.common.utils.FileUtil;
import com.cgnpc.scp.common.utils.JacksonUtil;
import com.cgnpc.scp.common.utils.ListUtil;
import com.cgnpc.scp.common.utils.NumberUtil;
import com.cgnpc.scp.common.utils.RequestUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.hse.mybatis.entity.HseMeetingFile;
import com.cgnpc.scp.hse.mybatis.entity.HseMeetingInfo;
import com.cgnpc.scp.hse.service.IHseMeetingFileService;
import com.cgnpc.scp.hse.service.IHseMeetingInfoService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

/******************************
 * 用途说明: 调试HSE管理-会议附件信息
 * 作者姓名: yblrs
 * 创建时间: 2020/8/20 22:20
 ******************************/
@Controller
@RequestMapping("/scp/hse/meetingFile")
public class HseMeetingFileController {
    private static final Logger LOGGER = LoggerFactory.getLogger(HseMeetingFileController.class);

    @Autowired
    private CurrentUser currentUser;

    @Autowired
    private MessageSource messageSource;

    @Autowired
    private AppConstantService appConstantService;

    @Autowired
    private FileCenterService fileCenterService;

    @Autowired
    private IHseMeetingInfoService hseMeetingInfoService;

    @Autowired
    private IHseMeetingFileService hseMeetingFileService;

    @Autowired
    private DownloadFileService downloadFileService;

    @Autowired
    private IScpCommonFileUploadService scpCommonFileUploadService;

    @Autowired
    private RestTemplate restTemplate;

    public String devMode;

    @Value("${spring.profiles.usemock}")
    public void setDevMode(String dm) {
        devMode = dm;
    }

    /**********************************
     * 用途说明: 调试HSE管理-会议附件信息---上传附件
     * 参数说明: MultipartHttpServletRequest request, HttpServletResponse response
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试HSE管理-会议附件信息---上传附件")
    @UBA(module = "调试HSE管理", action = "上传会议附件", channel = OperatorType.Button)
    @RequestMapping(value = "/uploadFile", method = {RequestMethod.POST})
    @ResponseBody
    public AjaxResult uploadFile(MultipartHttpServletRequest request, HttpServletResponse response, HttpServletRequest httpRequest) {
//        if ("local".equals(devMode)) {
//            try {
//                String reqNeedMeetingInfoId = request.getParameter("needMeetingInfoId");
//                Map map = new HashMap();
//                map.put("needMeetingInfoId", reqNeedMeetingInfoId);
//                HttpHeaders headers = new HttpHeaders();
//                String path = System.getProperty("java.io.tmpdir") + System.currentTimeMillis();
//                File dir = new File(path);
//                FileUtil.mkdirs(dir);
//                MultiValueMap<String, Object> multiValueMap = FileUtils.tofile("uploadDocsFile", request.getFiles("uploadDocsFile"), path);
//                HttpEntity httpEntity = new HttpEntity(multiValueMap, headers);
//                ResponseEntity<AjaxResult> responseEntity = restTemplate.postForEntity(UrlUtil.expandURL("https://scp.cgnpc.com.cn/app-api/scp/hse/meetingFile/uploadFile", map.keySet()), httpEntity, AjaxResult.class, map);
//                AjaxResult body = responseEntity.getBody();
//                List data = (List) body.get("data");
//                Map o = (Map) data.get(0);
//                Map uploadDocsFile = (Map) o.get("uploadDocsFile");
//                List dataSrc = (List) uploadDocsFile.get("dataSrc");
//                ApiResult<List> apiResult = ApiResult.success(dataSrc);
//                ScpApiResult<List<ScpFileInfoVO>> scpApiResult = FileCenterService.parseApiResultToScpApiResult(apiResult);
//                o.put("uploadDocsFile", scpApiResult);
//                if (scpApiResult != null) {
//                    UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
//                    String loginUserInfoUserId = null;
//                    String loginUserInfoUserName = null;
//
//                    if (loginUserInfo != null) {
//                        loginUserInfoUserId = loginUserInfo.getUserId();
//                        loginUserInfoUserName = loginUserInfo.getUserName();
//                    }
//                    List<ScpFileInfoVO> resultFileInfoVOList = scpApiResult.getData();
//
//                    if (resultFileInfoVOList != null) {
//                        List<ScpCommonFileUpload> usedScpCommonFileUpload = new ArrayList<>();
//                        ScpCommonFileUpload scpCommonFileUpload = null;
//                        Date nowDate = new Date();
//                        SimpleDateFormat sdfYyyymmddHhmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        SimpleDateFormat sdfYyyymmdd = new SimpleDateFormat("yyyy-MM-dd");
//
//                        for (ScpFileInfoVO resultFileInfoVO : resultFileInfoVOList) {
//                            String usedId = IDHelper.uuidNew();
//                            resultFileInfoVO.setScpCommonFileUploadId(usedId);
//
//                            scpCommonFileUpload = new ScpCommonFileUpload();
//                            usedScpCommonFileUpload.add(scpCommonFileUpload);
//                            scpCommonFileUpload.setId(usedId);
//                            scpCommonFileUpload.setFileCenterTenantId(resultFileInfoVO.getTenantId());
//                            scpCommonFileUpload.setFileCenterAppId(resultFileInfoVO.getAppId());
//                            scpCommonFileUpload.setFileCenterAppName(resultFileInfoVO.getAppName());
//                            scpCommonFileUpload.setFileCenterFileId(NumberUtil.formatLongToString(resultFileInfoVO.getFileId()));
//                            scpCommonFileUpload.setFileCenterFileName(resultFileInfoVO.getFileName());
//                            scpCommonFileUpload.setFileCenterFileType(resultFileInfoVO.getFileType());
//                            scpCommonFileUpload.setFileCenterFileSize(NumberUtil.parseStringToLongWithNull(resultFileInfoVO.getFileSize()));
//                            scpCommonFileUpload.setFileCenterUrl(resultFileInfoVO.getUrl());
//                            scpCommonFileUpload.setFileCenterUploadUserCode(resultFileInfoVO.getUploadUserCode());
//                            scpCommonFileUpload.setFileCenterUploadUserName(resultFileInfoVO.getUploadUserName());
//                            scpCommonFileUpload.setFileCenterUploadTime(DateUtil.parseToDateWithNullNotError(sdfYyyymmddHhmmss, sdfYyyymmdd, resultFileInfoVO.getUploadTime()));
//                            scpCommonFileUpload.setFileCenterFileStatus(resultFileInfoVO.getFileStatus());
//                            scpCommonFileUpload.setCreateTime(nowDate);
//                            scpCommonFileUpload.setCreateUser(loginUserInfoUserId);
//                            scpCommonFileUpload.setCreateUserName(loginUserInfoUserName);
//                            scpCommonFileUpload.setLastUpdateTime(nowDate);
//                            scpCommonFileUpload.setLastUpdateUserName(loginUserInfoUserId);
//                            scpCommonFileUpload.setLastUpdateUserName(loginUserInfoUserName);
//                        }
//                        Locale reqLocale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
//                        scpCommonFileUploadService.save(loginUserInfo, reqLocale, usedScpCommonFileUpload);
//                    }
//                }
//                return responseEntity.getBody();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            return null;
//        }


        /**
         * @see com.cgnpc.cuddemo.funcInstance.controller.CudWinController#upfile(MultipartHttpServletRequest, MultipartFile, HttpServletResponse)
         */
        final String logInfo = "[HseMeetingFile_uploadFile_UUID_" + UUID.randomUUID().toString() + "]";
        AjaxResult ajaxResult = null;
        final List<Object> uploadFileResultList = new ArrayList<>();
        final List<Object> uploadFileDebugInfoList = new ArrayList<>();
        final boolean reqHeaderPrintDebugInfo = false;

        try {
            // reqHeaderPrintDebugInfo = "Y".equals(request.getHeader(RequestUtil.HEADER_CUSTOM_PRINT_DEBUG_INFO));

            if (reqHeaderPrintDebugInfo) {
                String reqHeaderInfo = RequestUtil.getHeaderInfo(request);
                LOGGER.info("{}reqHeaderInfo:{};", logInfo, reqHeaderInfo);
                uploadFileDebugInfoList.add(reqHeaderInfo);
            }

            // 获取当前的登录用户信息
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            // 获取请求的语言reqLocale，cookie需要包含lang=cn，或者lang=en
            Locale reqLocale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
            boolean usedNeedMeetingInfoId = true; // 是否需要会议id，默认需要，不需要needMeetingInfoId传递N；

            String reqNeedMeetingInfoId = request.getParameter("needMeetingInfoId");
            String reqMeetingInfoId = request.getParameter("meetingInfoId");
            List<MultipartFile> reqUploadDocsFileList = request.getFiles("uploadDocsFile");
            List<MultipartFile> reqUploadAudioFileList = request.getFiles("uploadAudioFile");
            int reqUploadDocsFileListSize = ListUtil.getListSizeWith0(reqUploadDocsFileList);
            int reqUploadAudioFileListSize = ListUtil.getListSizeWith0(reqUploadAudioFileList);

            if (reqUploadDocsFileListSize <= 0 && reqUploadAudioFileListSize <= 0) {
                return AjaxResultUtil.createErrorMessage(
                        "所有上传的文件数量必须大于0"
                );
            }

            // begin 校验文件类型
            boolean isSafeFileWithUploadFileDocsFile = reqUploadDocsFileListSize <= 0 || FileUtil.isSafeFileWithUploadFile(reqUploadDocsFileList);
            boolean isSafeFileWithUploadFileAudioFile = reqUploadAudioFileListSize <= 0 || FileUtil.isSafeFileWithUploadFile(reqUploadAudioFileList);

            if (!isSafeFileWithUploadFileDocsFile || !isSafeFileWithUploadFileAudioFile) {
                return AjaxResultUtil.createErrorMessage(
                        "上传文件类型不匹配"
                );
            }
            // end 校验文件类型

            usedNeedMeetingInfoId = !"N".equals(reqNeedMeetingInfoId);

            LOGGER.info("{}printInfo;reqMeetingInfoId:{};reqNeedMeetingInfoId:{};usedNeedMeetingInfoId:{};"
                    , logInfo
                    , reqMeetingInfoId, reqNeedMeetingInfoId, usedNeedMeetingInfoId
            );

            String dbHseMeetingInfoId = null;

            if (usedNeedMeetingInfoId) {
                if (StringUtil.isNullOrSpace(reqMeetingInfoId)) {
                    LOGGER.info("{}printInfo;reqMeetingInfoId is null or space;"
                            , logInfo
                    );
                    return AjaxResultUtil.createI18nErrorDefaultMessage(reqLocale, messageSource, uploadFileResultList);
                }

                HseMeetingInfo dbHseMeetingInfo = hseMeetingInfoService.queryByIdOnlyInfo(reqMeetingInfoId);

                if (dbHseMeetingInfo == null) {
                    LOGGER.error("{}dbHseMeetingInfo is null", logInfo);
                    return AjaxResultUtil.createI18nErrorDefaultMessage(reqLocale, messageSource, uploadFileResultList);
                }

                dbHseMeetingInfoId = dbHseMeetingInfo.getId();
            }

            // 上传文件结果
            //{
            //    "responseId": "1",
            //    "code": "200",
            //    "msg": "成功",
            //    "data": [
            //        {
            //            "status": true,
            //            "msg": "成功",
            //            "tenantId": "1",
            //            "appId": "1260840145154740225",
            //            "appName": "智能调试一体化平台",
            //            "fileId": "1316276450856275969",
            //            "fileName": "getBpmPscActInfoResponse.json",
            //            "fileType": "json",
            //            "fileSize": "493",
            //            "url": "http://aep-fastdfs1-t.gnpjvc.cgnpc.com.cn:8888/group2/M00/08/9C/CmQYEl-GpZeAd3P4AAAB7foW9U026.json",
            //            "downloadCount": null,
            //            "previewCount": null,
            //            "uploadUserCode": "P622400",
            //            "uploadUserName": "why ",
            //            "uploadTime": "2020-10-14 15:15:35",
            //            "fileStatus": "正常"
            //        },
            //        {
            //            "status": true,
            //            "msg": "成功",
            //            "tenantId": "1",
            //            "appId": "1260840145154740225",
            //            "appName": "智能调试一体化平台",
            //            "fileId": "1316276450914996225",
            //            "fileName": "getPermissions_response.json",
            //            "fileType": "json",
            //            "fileSize": "404",
            //            "url": "http://aep-fastdfs1-t.gnpjvc.cgnpc.com.cn:8888/group2/M00/08/84/CmQYD1-GpZeATSd_AAABlIA_QVk45.json",
            //            "downloadCount": null,
            //            "previewCount": null,
            //            "uploadUserCode": "P622400",
            //            "uploadUserName": "why ",
            //            "uploadTime": "2020-10-14 15:15:35",
            //            "fileStatus": "正常"
            //        }
            //    ]
            //}

            // begin 上传文档到中台文件服务器
            ScpApiResult<List<ScpFileInfoVO>> apiResultDocsFile = fileCenterService.uploadFileToFileCenterWithScpApiResult(
                    logInfo
                    , reqLocale, loginUserInfo, reqUploadDocsFileList
                    , reqHeaderPrintDebugInfo, uploadFileResultList, uploadFileDebugInfoList
            );

            LOGGER.info("{}printInfo;apiResultDocsFile:{};"
                    , logInfo
                    , JacksonUtil.writeValueAsString(apiResultDocsFile)
            );

            Map<String, Object> uploadDocsFileResultMap = new HashMap<>();
            uploadDocsFileResultMap.put("uploadDocsFile", apiResultDocsFile);
            uploadFileResultList.add(uploadDocsFileResultMap);

            if (usedNeedMeetingInfoId) {
                List<HseMeetingFile> usedHseMeetingFileListWithDoc = parseApiResultWithUploadFileInfo(
                        logInfo,
                        apiResultDocsFile,
                        dbHseMeetingInfoId,
                        HseMeetingFile.MEETINGFILETYPE_1_DOC
                );
                hseMeetingFileService.save(loginUserInfo, reqLocale, usedHseMeetingFileListWithDoc);
            }

            // end 上传文档到中台文件服务器

            // begin 上传录音文件到中台文件服务器
            ScpApiResult<List<ScpFileInfoVO>> apiResultAudioFile = fileCenterService.uploadFileToFileCenterWithScpApiResult(
                    logInfo
                    , reqLocale, loginUserInfo, reqUploadAudioFileList
                    , reqHeaderPrintDebugInfo, uploadFileResultList, uploadFileDebugInfoList
            );

            LOGGER.info("{}printInfo;apiResultAudioFile:{};"
                    , logInfo
                    , JacksonUtil.writeValueAsString(apiResultAudioFile)
            );

            Map<String, Object> uploadAudioFileResultMap = new HashMap<>();
            uploadAudioFileResultMap.put("uploadAudioFile", apiResultAudioFile);
            uploadFileResultList.add(uploadAudioFileResultMap);

            if (usedNeedMeetingInfoId) {
                List<HseMeetingFile> usedHseMeetingFileListWithAudio = parseApiResultWithUploadFileInfo(
                        logInfo,
                        apiResultAudioFile,
                        dbHseMeetingInfoId,
                        HseMeetingFile.MEETINGFILETYPE_2_AUDIO
                );
                hseMeetingFileService.save(loginUserInfo, reqLocale, usedHseMeetingFileListWithAudio);
            }

            // end 上传录音文件到中台文件服务器

            ajaxResult = AjaxResultUtil.createI18nSuccessDefaultMessage(
                    reqLocale
                    , messageSource
                    , uploadFileResultList
            );
        } catch (Throwable t) {
            LOGGER.error("{}error;", logInfo, t);
            ajaxResult = AjaxResultUtil.createI18nErrorDefaultMessage(request, messageSource, uploadFileResultList);
        } finally {
            if (ajaxResult != null) {
                ajaxResult.put("___debugInfo", uploadFileDebugInfoList);
            }
        }

        return ajaxResult;
    }

    public List<HseMeetingFile> parseApiResultWithUploadFileInfo(
            final String logInfo,
            ScpApiResult<List<ScpFileInfoVO>> apiResultWithUploadFile,
            String hseMeetingInfoId,
            int meetingFileType
    ) {
        List<HseMeetingFile> usedHseMeetingFileList = new ArrayList<>();
        List<ScpFileInfoVO> apiResultWithUploadFileDataList = apiResultWithUploadFile == null ? null : apiResultWithUploadFile.getData();

        if (ListUtil.getListSizeWith0(apiResultWithUploadFileDataList) > 0) {
            HseMeetingFile hseMeetingFile = null;
            SimpleDateFormat sdfYyyymmddHhmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdfYyyymmdd = new SimpleDateFormat("yyyy-MM-dd");

            //{
            //    "status": true,
            //    "msg": "成功",
            //    "tenantId": "1",
            //    "appId": "1260840145154740225",
            //    "appName": "智能调试一体化平台",
            //    "fileId": "1316276450914996225",
            //    "fileName": "getPermissions_response.json",
            //    "fileType": "json",
            //    "fileSize": "404",
            //    "url": "http://aep-fastdfs1-t.gnpjvc.cgnpc.com.cn:8888/group2/M00/08/84/CmQYD1-GpZeATSd_AAABlIA_QVk45.json",
            //    "downloadCount": null,
            //    "previewCount": null,
            //    "uploadUserCode": "P622400",
            //    "uploadUserName": "why ",
            //    "uploadTime": "2020-10-14 15:15:35",
            //    "fileStatus": "正常"
            //}

            ScpFileInfoVO uploadFile = null;

            for (int aaa = 0; aaa < apiResultWithUploadFileDataList.size(); aaa++) {
                try {
                    uploadFile = apiResultWithUploadFileDataList.get(aaa);
                    String uploadFileTenantId = uploadFile.getTenantId();
                    String uploadFileAppId = uploadFile.getAppId();
                    String uploadFileAppName = uploadFile.getAppName();
                    Long uploadFileFileId = uploadFile.getFileId();
                    String uploadFileFileName = uploadFile.getFileName();
                    String uploadFileFileType = uploadFile.getFileType();
                    String uploadFileFileSize = uploadFile.getFileSize();
                    String uploadFileUrl = uploadFile.getUrl();
                    String uploadFileUploadTime = uploadFile.getUploadTime();
                    String uploadFileUploadUserCode = uploadFile.getUploadUserCode();
                    String uploadFileUploadUserName = uploadFile.getUploadUserName();

                    Long usedFileSize = NumberUtil.parseStringToLongWithNull(uploadFileFileSize);
                    Date usedUploadTime = DateUtil.parseToDateWithNullNotError(sdfYyyymmddHhmmss, sdfYyyymmdd, StringUtil.formatObjectToString(uploadFileUploadTime));
                    String usedFileCenterFileId = NumberUtil.formatLongToString(uploadFileFileId);

                    hseMeetingFile = new HseMeetingFile();
                    usedHseMeetingFileList.add(hseMeetingFile);

                    hseMeetingFile.setMeetingInfoId(hseMeetingInfoId);
                    hseMeetingFile.setScpCommonFileUploadId(uploadFile.getScpCommonFileUploadId());
                    hseMeetingFile.setFileType(uploadFileFileType);
                    hseMeetingFile.setFileOriginalName(uploadFileFileName);
                    hseMeetingFile.setFileName(uploadFileFileName);
                    hseMeetingFile.setFileSizeByte(usedFileSize);
                    hseMeetingFile.setFilePath(null);
                    hseMeetingFile.setFileWebPath(uploadFileUrl);
                    hseMeetingFile.setCreateTime(usedUploadTime);
                    hseMeetingFile.setCreateUser(uploadFileUploadUserCode);
                    hseMeetingFile.setCreateUserName(uploadFileUploadUserName);
                    hseMeetingFile.setLastUpdateTime(usedUploadTime);
                    hseMeetingFile.setLastUpdateUser(uploadFileUploadUserCode);
                    hseMeetingFile.setLastUpdateUserName(uploadFileUploadUserName);
                    hseMeetingFile.setMeetingFileType(meetingFileType);
                    hseMeetingFile.setFileCenterTenantId(uploadFileTenantId);
                    hseMeetingFile.setFileCenterAppId(uploadFileAppId);
                    hseMeetingFile.setFileCenterAppName(uploadFileAppName);
                    hseMeetingFile.setFileCenterFileId(usedFileCenterFileId);
                    hseMeetingFile.setFileCenterFileSize(usedFileSize);
                    hseMeetingFile.setFileCenterUrl(uploadFileUrl);
                } catch (Exception e) {
                    LOGGER.error("{}hseMeetingFile.error;"
                            , logInfo
                    );
                    throw e;
                }
            }
        }

        return usedHseMeetingFileList;
    }

}
